package com.qyer.search.model.result;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.qyer.search.model.lastminute.SKU;
import com.qyer.search.model.lastminute.ZSKU;
import com.qyer.search.utils.ListUtils;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.Set;

/**
 * Created by tangzheng on 16/7/18.
 */
public class SearchSKUs {

  @JsonProperty
  protected List<ZSKU> skus;
  @JsonProperty("skus_size")
  protected int packageSize;
  @JsonIgnore
  protected Set<Integer> idSet;

  public SearchSKUs() {
    this.skus = Lists.newArrayListWithExpectedSize(50);
    this.idSet = Sets.newHashSetWithExpectedSize(skus.size());
    this.packageSize = 0;
  }

  public SearchSKUs(int listSize) {
    this.skus = Lists.newArrayListWithExpectedSize(listSize);
    this.idSet = Sets.newHashSetWithExpectedSize(listSize);
    this.packageSize = 0;
  }

  // 去重
  public void addSku(ZSKU sku) {
    int id = sku.getId();
    if (!idSet.contains(id)) {
      this.skus.add(sku);
      this.idSet.add(id);
      this.packageSize = this.idSet.size();
    }
  }

  // 这里不判断去重, 因为去重的工作在addSku做了, 这个功能是给排序准备的
  public void addSkus(List<ZSKU> skus) {
    if (CollectionUtils.isEmpty(skus)) {
      return;
    }
    this.skus.addAll(skus);
    this.packageSize += skus.size();
  }

  public List<ZSKU> getSkus() {
    return skus;
  }

  public void setSkus(List<ZSKU> skus) {
    this.skus = skus;
  }

  public int getPackageSize() {
    return packageSize;
  }

  public void setPackageSize(int packageSize) {
    this.packageSize = packageSize;
  }

  public Set<Integer> getIdSet() {
    return idSet;
  }

  public void setIdSet(Set<Integer> idSet) {
    this.idSet = idSet;
  }

  public void resize(int limit){
    this.skus = ListUtils.ToSubList(this.skus, 0, limit);
    Set<Integer> set = Sets.newHashSetWithExpectedSize(limit);
    for(int i = 0; i < this.skus.size(); i++){
      set.add(this.skus.get(i).getId());
    }
    this.idSet = set;
  }
}
